package com.haier.dreambox.demo.activity;

import android.app.ProgressDialog;
import android.net.ConnectivityManager;
import android.util.Log;
import android.view.View;
import android.widget.*;
import com.haier.dreambox.demo.BaseActivity;
import com.haier.dreambox.demo.R;
import com.haier.dreambox.demo.bean.Event.HaieruDeviceListChangeEvent;
import com.haier.dreambox.demo.utils.DialogUtil;
import com.haier.dreambox.demo.utils.IntentUtils;
import com.haier.dreambox.demo.utils.ToastUtils;
import com.haier.dreambox.lib.usdklib.wifi.WifiAdmin;
import com.haier.dreambox.lib.usdklib.wifi.WifiUtil;
import com.haier.uhome.usdk.api.uSDKDevice;
import com.haier.uhome.usdk.api.uSDKErrorConst;
import org.androidannotations.annotations.*;

import java.util.*;

/**
 * Created by smalant on 14/12/26.
 */

@EActivity(R.layout.activity_dev_bind_set)
public class DevBindSetActivity extends BaseActivity {

    private static final String TAG = DevBindSetActivity.class.getSimpleName();

    @ViewById(R.id.id_imageButton_common_head_back)
    ImageButton imageButton_back;

    @ViewById(R.id.id_textView_common_head_center_text)
    TextView textView_title;

    @ViewById(R.id.id_button_next)
    Button button_next;

    @ViewById(R.id.id_textview_wifi_ssid)
    TextView textView_wifiSsid;

    @ViewById(R.id.id_button_go_to_wifi)
    Button button_goWifi;

    @ViewById(R.id.id_layout_linear_wifi_not_available)
    LinearLayout linearLayout_wifiNotAvailable;

    @ViewById(R.id.id_editText_wifi_pass)
    EditText editText_pass;

    @SystemService
    ConnectivityManager connectivityManager;

    @Bean
    ToastUtils toastUtils;

    ProgressDialog progressDialog;

    @AfterViews
    void main() {
        textView_title.setText("配置设备");
        String wifiSsidStringWithWildCards = textView_wifiSsid.getText().toString();
        textView_wifiSsid.setText(String.format(wifiSsidStringWithWildCards, getCurrentWifiSsid()));

        if (!WifiUtil.isWifiConnected(getApplicationContext())) {
            linearLayout_wifiNotAvailable.setVisibility(View.VISIBLE);
        }

        progressDialog = DialogUtil.buildProgressDialog(this, "绑定中...", new Runnable() {
            @Override
            public void run() {
                smartConfigFinish();
            }
        });

    }


    public void onEvent(HaieruDeviceListChangeEvent event) {

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (WifiUtil.isWifiConnected(getApplicationContext())
                && linearLayout_wifiNotAvailable.isShown()) {
            linearLayout_wifiNotAvailable.setVisibility(View.GONE);
        } else if (!WifiUtil.isWifiConnected(getApplicationContext())
                && !linearLayout_wifiNotAvailable.isShown()) {
            linearLayout_wifiNotAvailable.setVisibility(View.VISIBLE);
        }

    }

    @Click(R.id.id_imageButton_common_head_back)
    void backClick() {
        finish();
    }


    @Click(R.id.id_button_go_to_wifi)
    void gotoWifi() {
        startActivity(IntentUtils.getWifiSettingIntent());
    }


    @Click(R.id.id_button_next)
    void set() {

        progressDialog.show();

        uSDKErrorConst sdkErrorConst =
                sdkManager.smartConfig(getCurrentWifiSsid(), editText_pass.getText().toString());

        if (sdkErrorConst.RET_USDK_OK == sdkErrorConst) {
            //3s后获取即将绑定的设备
            getPendingDeviceTimer = new Timer();
            getPendingDeviceTimer.scheduleAtFixedRate(new TimerTask() {
                @Override
                public void run() {
                    Log.i(TAG, "getPendingDeviceTimer > run ...");
                    List<uSDKDevice> deviceList = sdkManager.getPendingDeviceList();
                    if (deviceList != null && deviceList.size() > 0) {
                        //如果存在即将绑定的设备
                        getPendingDeviceTimer.cancel();

                        for (uSDKDevice device : deviceList) {
                            toastUtils.showShort(DevBindSetActivity.this, "要绑定的设备Mac: " + device.getDeviceMac());
                        }

                        DevBindUploadInfoActivity_.intent(DevBindSetActivity.this).start();
                        progressDialog.dismiss();

                    }
                    //超时
                    if (!sdkManager.isInBinding()) {
                        getPendingDeviceTimer.cancel();
                        toastUtils.showShort(DevBindSetActivity.this, "等待上报新绑定设备时间已经结束");
                        progressDialog.dismiss();
                    }
                }
            }, 3000, 500);
        } else {
            progressDialog.dismiss();
        }

        toastUtils.showShort(this, sdkErrorConst == null ? "NULL" : sdkErrorConst.getValue());

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //cancel Timer
        smartConfigFinish();

    }

    private void smartConfigFinish() {
        getPendingDeviceTimer.cancel();
        sdkManager.smartConfigReset();
    }

    Timer getPendingDeviceTimer = new Timer();

    public String getCurrentWifiSsid() {
        return WifiAdmin.getInstance(this).getCurrentWifiInfo().getSSID().replaceAll("\"", "");
    }


    @Receiver(actions = ConnectivityManager.CONNECTIVITY_ACTION)
    protected void onNetworkChange() {
        if (WifiUtil.isWifiConnected(getApplicationContext())) {
            if (linearLayout_wifiNotAvailable.isShown()) {
                linearLayout_wifiNotAvailable.setVisibility(View.GONE);
            }
        } else {
            if (!WifiUtil.isWifiConnected(getApplicationContext())
                    && !linearLayout_wifiNotAvailable.isShown()) {
                linearLayout_wifiNotAvailable.setVisibility(View.VISIBLE);
            }
        }
    }

}
